package com.cloudcc.mobile.view.test;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.JsonRequest;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.MakeTureDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.VerificateUtils;
import com.cloudcc.mobile.view.mymodel.Tiyanmodel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 测试第一步骤 输入手机号码
 *
 * @author wangzhiqiang
 * @Description: TODO()
 * @date 2016-3-2 下午3:34:30
 */
public class Step1Fragment extends BaseStepFragment implements TestStepActivity.OnSendSMSListener {

    @Bind(R.id.tiyan_information_text)
    TextView tiyanInformationText;
    @Bind(R.id.tiyan_make_bt)
    TextView tiyanMakeBt;
    private String mEns = Locale.getDefault().getLanguage();
    @Bind(R.id.test_done)
    Button btn_done;

    @Bind(R.id.tijiao)
    Button btn_tijiao;

    @Bind(R.id.edt_yanzheng)
    EditText edt_yanzheng;

    @Bind(R.id.test_et1)
    EditText et_test_phone;
    public int ceshi = 120;
    MakeTureDialog dialog;

    private int type = 1;//1--使用手机号体验  2--使用邮箱体验

    @Override
    public void init() {
        super.init();

        initEditText();
    }

    String inputNumber = null;

    private void initEditText() {
        dialog = new MakeTureDialog(getActivity(), R.style.DialogLoadingTheme);
        ImageSpan imgSpan = new ImageSpan(getActivity(), R.drawable.tiyan_youxiang_information);
        SpannableString spannableString = new SpannableString(getString(R.string.tiyan_shuoming));
        spannableString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tiyanInformationText.setText(spannableString);
        et_test_phone.setInputType(InputType.TYPE_CLASS_NUMBER);
        edt_yanzheng.addTextChangedListener(new

    TextWatcher() {

        @Override
        public void onTextChanged (CharSequence s,int start, int before, int count){
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged (CharSequence s,int start, int count,
        int after){
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged (Editable s){
            // TODO Auto-generated method stub
            if (TextUtils.isEmpty(edt_yanzheng.getText().toString().trim())) {
                btn_tijiao.setEnabled(false);
                btn_tijiao.setBackgroundResource(R.drawable.shape_corner6_stroke1_b9b9b9_sloid);
            } else {
                btn_tijiao.setEnabled(true);
                btn_tijiao.setBackgroundResource(R.drawable.shape_corner6_stroke1_0d74d4_sloid);
            }

        }
    });
        et_test_phone
                .setOnEditorActionListener(new EditText.OnEditorActionListener()

    {

        @Override
        public boolean onEditorAction (TextView v,int actionId,
        KeyEvent event){
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) v
                    .getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            clickDone();
            return true;
        }
        return false;
    }
    });
        btn_tijiao.setOnClickListener(new

    OnClickListener() {

        @Override
        public void onClick (View v){
            inputNumber = edt_yanzheng.getText().toString().trim();
            if (TextUtils.isEmpty(inputNumber)) {
                dialog.show();
                dialog.setTitle(getString(R.string.no_yanzhengma));

                return;
            }
            boolean isOk = ((TestStepActivity) getActivity())
                    .verifyVerNumber(inputNumber);
            if (!isOk) {
                dialog.show();
                dialog.setTitle(getString(R.string.error_yanzhengma));
                return;
            }
            insertLeads();
            // 进入选中帐号服务
            MoveNextStep();

        }
    });
        tiyanMakeBt.setOnClickListener(new

    OnClickListener() {
        @Override
        public void onClick (View v){
            changeBtYanzhengma();
            et_test_phone.setText("");
            edt_yanzheng.setText("");
            if (type == 1) {
                type = 2;
                et_test_phone.setInputType(InputType.TYPE_CLASS_TEXT);
                et_test_phone.setHint(R.string.tiyan_ed_email);
                btn_done.setText(getString(R.string.tiyan_yanzhengma_email));
                tiyanMakeBt.setText(getString(R.string.tiyan_bt_phone));
            } else {
                type = 1;
                et_test_phone.setInputType(InputType.TYPE_CLASS_NUMBER);
                et_test_phone.setHint(R.string.tiyan_ed_phone);
                btn_done.setText(getString(R.string.tiyan_yanzhengma_phone));
                tiyanMakeBt.setText(getString(R.string.tiyan_bt_email));
            }
        }
    });
}

    public void changeBtYanzhengma() {
        handler.removeCallbacks(runnable);
        btn_done.setEnabled(true);
        btn_done.setBackgroundResource(R.drawable.shape_corner6_stroke1_26b93d_sloid);
        if (type == 1) {
            btn_done.setText(getString(R.string.tiyan_yanzhengma_email));
        } else {
            btn_done.setText(getString(R.string.tiyan_yanzhengma_phone));
        }
    }

    /**
     * 插入潜在客户
     */
    private void insertLeads() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("name", "安卓手机快速体验");
        if (type == 1) {
            data.put("phone", phone);
        } else {
            data.put("email", email);
        }
        data.put("qzkhly", "CloudCC");
        data.put("qzkhzt", "1，原始进入系统尚未处理");
        //		data.put("isMobile", "true");
        data.put("isMobileRegister", "true");
        List aa = new ArrayList();
        aa.add(data);
        RequestParams params = new RequestParams();
        params.put("serviceName", "insert");
        params.put("objectApiName", "Lead");
        params.put("data", GsonUtil.Object2Json(aa));
        params.put("binding", mParentActivity.testBinding);
        AsyncClient.getInstance().post(
                "http://app.cloudcc.com/distributor.action", params,
                new myJsonRequest());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onSuccess() {
        dialog.show();
        dialog.setTitle(getString(R.string.time_yanzhengma));
    }

    @Override
    public void onFailure() {
        changeBtYanzhengma();
    }

private class myJsonRequest extends JsonRequest {

    @Override
    public void handleFailure(ErrorInfo arg0) {
        dismissWainting();
    }

    @Override
    public void handleSuccess(JsonObject arg0, String arg1) {
        dismissWainting();
        try {
            String json = arg0.get("data").toString();
            Gson gson = new Gson();
            Tiyanmodel ss = gson.fromJson(json,
                    Tiyanmodel.class);
            String id = ss.ids.get(0).id;
            mParentActivity.SetId(id);
        } catch (Exception e) {
            mParentActivity.SetId("");
        }

    }

}

    String phone = null;
    String email = null;

    //获取验证码
    @OnClick(R.id.test_done)
    public void clickDone() {
        mParentActivity.resetSMSListener();
        mParentActivity.sendVerSMS(this);
        if (type == 1) {
            boolean isMobile = VerificateUtils.isMobile(et_test_phone.getText()
                    .toString().trim());
            if (!isMobile) {
                dialog.show();
                dialog.setTitle(getString(R.string.tiyan_phone_error));
                return;
            }

            mParentActivity.sendVerSMS(et_test_phone.getText().toString().trim(), type);
            phone = et_test_phone.getText().toString().trim();
        } else {
            boolean isEmail = Tools.isEmail(et_test_phone.getText()
                    .toString());
            if (!isEmail) {
                dialog.show();
                dialog.setTitle(getString(R.string.tiyan_email_error));
                return;
            }
            mParentActivity.sendVerSMS(et_test_phone.getText().toString().trim(), type);
            email = et_test_phone.getText().toString();

        }
        btn_done.setEnabled(false);
        btn_done.setBackgroundResource(R.drawable.shape_corner6_stroke1_b9b9b9_sloid);
        handler.postDelayed(runnable, 1000);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ceshi--;
            if ("zh".equals(mEns)) {
                btn_done.setText("验证码" + "[" + ceshi + "s]");
            } else {
                btn_done.setText(ceshi + "s");
            }
            if (ceshi == 0) {
                if ("zh".equals(mEns)) {
                    btn_done.setText("重新获取验证码");
                } else {
                    btn_done.setText("To obtain the verification code");
                }

                btn_done.setBackgroundResource(R.drawable.shape_corner6_stroke1_26b93d_sloid);
                btn_done.setEnabled(true);
                ceshi = 120;
            } else {
                handler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.test_step1;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(runnable);
        super.onDestroy();
    }
}
